function [Res epT]=bciGetFeedbackPerformance(testOnRun,doRetrain)

global GLOBALbci;
global GLOBALtrainDat;
global GLOBALtrainSet;
global MEMepoch;

if length(testOnRun)>1,
    error('Only single runs can be tested by this function.');
end

bci=GLOBALbci;

label=GLOBALtrainDat{testOnRun}.trainLabel';

if nargin <2,
    doRetrain=bci.param.retrainClassifier;
end

if ~isfield(GLOBALtrainDat{testOnRun},'isRetrainTrial'),
    isRetrainTrial = true(size(label'));
elseif sum(GLOBALtrainDat{testOnRun}.isRetrainTrial)==0,
    isRetrainTrial = true(size(label'));
else
    isRetrainTrial=GLOBALtrainDat{testOnRun}.isRetrainTrial;
end
% trialReset=[isRetrainTrial(1) diff(isRetrainTrial)]>0;% here retrain is performed only at changing conditions. if successive trials of same condition not considered!

label=label(isRetrainTrial);
% trialReset = trialReset(isRetrainTrial);
prediction = zeros(size(label));
epT = bciTransformData(GLOBALtrainDat{testOnRun}.trainEpoch(:,:,1),bci,1);
epT=zeros(length(label),size(epT,2));
cond = GLOBALbci.eventsToClassify;
for k=1:length( label),
    epT(k,:) = bciTransformData(GLOBALtrainDat{testOnRun}.trainEpoch(:,:,k),bci,1);
    prediction(k)=bci.param.testFunc(bci,epT(k,bci.featureMask));
    if doRetrain,% && trialReset(k),
        labelIdx = 1:k;
        MEMepoch(:,:,k)=GLOBALtrainDat{testOnRun}.trainEpoch(:,:,k);
        [bci,Train]=bciRetrainClassifier(bci,labelIdx,label(labelIdx));
        fprintf('%i RetrainSize: ',k);
        for ci = 1:length(cond),
            fprintf('%i ',sum(Train.label==cond(ci)));
        end
        fprintf('\n');
    end
end

if doRetrain && bci.param.retrainClassifier,
    GLOBALtrainSet = Train;
    GLOBALbci = bci;
end

Res.label=label;
Res.prediction = prediction;
Res.predAcc=sum(prediction==label)/length(label);

fprintf('PredAcc: %3.2f\n',Res.predAcc*100);


for ci = 1:length(cond),    
    if any(label==cond(ci)),
        Res.recall(ci) = sum(prediction==cond(ci)&label==cond(ci))/sum(label==cond(ci));
        Res.precision(ci) = sum(prediction==cond(ci)&label==cond(ci))/...
            (sum(prediction==cond(ci)&label==cond(ci))+sum(prediction==cond(ci)&label~=cond(ci)));
        fprintf('Recall Cond %i: %3.2f Precision Cond %i : %3.2f\n',...
                cond(ci),Res.recall(ci)*100,cond(ci), Res.precision(ci)*100);
    end
end

